//
//  SettingListViewController.m
//  MoneyBook
//
//  Created by MyoungHo Kim on 11. 7. 8..
//  Copyright 2011 Daum. All rights reserved.
//

#import "SettingListViewController.h"

NSString * const kCellIdentifier = @"MyIdentifier";

@implementation SettingListViewController
@synthesize dataSourceArray = _dataSourceArray;

/////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _isEditMode = NO;
        [self showDoneMode];
    }
    
    return self;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc{
    [_dataSourceArray release];
    [super dealloc];
}
#pragma mark - View lifecycle
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad{
    [self.tableView setAllowsSelectionDuringEditing:YES];
    [super viewDidLoad];
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidUnload{
    self.dataSourceArray = nil;
    [super viewDidUnload];
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

/////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
	[super shouldAutorotateToInterfaceOrientation:interfaceOrientation];
    return YES;
}

/////////////////////////////////////////////////////////////////////////////////////////////////
- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    
}
#pragma mark -
#pragma mark Super methods
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)showDoneMode{
    _isEditMode = NO;
    [self.tableView setEditing:NO animated:YES];
    UIToolbar* toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 100, 45)];
    
    NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
    
    UIBarButtonItem *editBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
                                                                             target:self
                                                                             action:@selector(showEditMode)];
    editBtn.style = UIBarButtonItemStyleBordered;
    [buttons addObject:editBtn];
    [editBtn release];
    
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                            target:nil
                                                                            action:nil];
    [buttons addObject:spacer];
    [spacer release];
    
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                            target:self
                                                                            action:@selector(addAction)];
    addBtn.style = UIBarButtonItemStyleBordered;
    [buttons addObject:addBtn];
    [addBtn release];
    
    [toolbar setItems:buttons animated:NO];
    [buttons release];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                              initWithCustomView:toolbar];
    [toolbar release];
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)showEditMode{
    if([_dataSourceArray count]==1){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"경고" message:@"최소 한개는 있어야 합니다." delegate:nil cancelButtonTitle:@"확인" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }else{
        _isEditMode = YES;
        [self.tableView setEditing:YES animated:YES];
        UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                                  target:self
                                                                                  action:@selector(showDoneMode)];
        [self.navigationItem setRightBarButtonItem:rightBtn];        
        [rightBtn release];
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
-(void)moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath tableName:(NSString*)tableName{
    //    NSLog(@"moveRowAtIndexPath %d => %d",fromIndexPath.row, toIndexPath.row);    
    NSUInteger fromRow = [fromIndexPath row];
    NSUInteger toRow = [toIndexPath row];
    
    
    id object = [[_dataSourceArray objectAtIndex:fromRow] retain];
    [_dataSourceArray removeObjectAtIndex:fromRow];
    
    [_dataSourceArray insertObject:object atIndex:toRow];     
    [object release];
    
    
    int start = 0;
    int end = 0;
    if(fromRow>toRow){
        start = toRow;
        end = fromRow;
    }else{
        start = fromRow;
        end = toRow;
    }
    
    int index = 0;
    SQLHandler *sql = [SQLHandler sharedInstance];
    for(NSDictionary *dic in _dataSourceArray){
        if(index>=start && index<=end){
            [sql updateOrder:tableName pkId:[dic objectForKey:[NSString stringWithFormat:@"%@_id", tableName]] order:[NSNumber numberWithInt:index]];
//            NSLog(@"update order:%d => %d", [[dic objectForKey:@"item_group_order"] intValue], index);
        }
        index++;
    }
}
#pragma mark -
#pragma mark UITableViewDelegate
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
//- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"canMoveRowAtIndexPath");
//
//    return YES;
//}
//- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath{
//    NSLog(@"targetIndexPathForMoveFromRowAtIndexPath %d => %d",sourceIndexPath.row, proposedDestinationIndexPath.row);
//}
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath{
}

#pragma mark -
#pragma mark UITableViewDataSource
/////////////////////////////////////////////////////////////////////////////////////////////////
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_dataSourceArray count];
}
/////////////////////////////////////////////////////////////////////////////////////////////////
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
	if (cell == nil){
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.textColor = [UIColor grayColor];
        cell.textLabel.highlightedTextColor = [UIColor blackColor];
        cell.textLabel.font = [UIFont systemFontOfSize:12.0];
        cell.showsReorderControl = YES;
	}
	cell.textLabel.text = [[_dataSourceArray objectAtIndex:indexPath.row] objectForKey:@"title"];
	return cell;
}
@end
